package com.fhhst.prodroid;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.lamerman.FileDialog;
import com.lamerman.SelectionMode;

public class MainActivity extends Activity {

	private TextView mTitleTextView;
	private TextView mDumpTextView;
	private ScrollView mScrollView;
	private ToggleButton btnHeat;
	private ToggleButton btnBed;
	private Spinner spHeat;
	private Spinner spBed;

	private boolean progressOpen;

	// Progress Dialog
	private ProgressDialog pDialog;
	public static final int progress_bar_type = 2;

	public static final String KEY_progessOpen = "progessOpen";

	// private Printer lPrinter;
	private Printcore lPrintcore;

	private Menu menu;

	private final String TAG = "prodroid";

	// file dialog constants
	private final int REQUEST_SAVE = 2;
	private final int REQUEST_LOAD = 3;

	private List<String> data = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		
		//TODO: Save all necessary fields  
		if (savedInstanceState != null) {
			progressOpen = savedInstanceState.getBoolean(KEY_progessOpen);			
			
			
			
			
		}

		setContentView(R.layout.activity_main);
		getData().clear();
		lPrintcore = new Printcore(this);

		linkViews();
		addListenerOnButton();

		lPrintcore.reset();// reset on printer connect maybe its already there
		// updateMenuTitles();

	}

	/**
	 * Find Views of the GUI elements
	 */
	private void linkViews() {
		// TextViews
		mTitleTextView = (TextView) findViewById(R.id.demoTitle);
		mDumpTextView = (TextView) findViewById(R.id.demoText);

		// ScrollViews
		mScrollView = (ScrollView) findViewById(R.id.demoScroller);

		// Buttons
		btnHeat = (ToggleButton) findViewById(R.id.btnHeat);
		btnBed = (ToggleButton) findViewById(R.id.btnBed);

		// Spinner
		spHeat = (Spinner) findViewById(R.id.spHeat);
		spBed = (Spinner) findViewById(R.id.spBed);

	}

	private void addListenerOnButton() {
		btnHeat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (btnHeat.isChecked()) {
					lPrintcore.setHeatTemp(100); // Take Value from Spinner
													// //TODO: Insert correct
													// value from spinner
				} else { // Turn Off
					lPrintcore.setHeatTemp(0);

				}
			}
		});
		btnBed.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (btnBed.isChecked()) {
					lPrintcore.setBedTemp(100); // Take Value from Spinner
												// //TODO: Insert correct value
												// from spinner
				} else { // Turn Off
					lPrintcore.setBedTemp(0);
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		this.menu = menu;
		return true;
	}

	public void updateMenuTitles() {
		if (menu != null) {
			MenuItem connectMenuItem = menu.findItem(R.id.action_connect);
			if (lPrintcore.isOnline()) {
				connectMenuItem.setTitle(R.string.lblBtnDisconnect);

			} else {
				connectMenuItem.setTitle(R.string.lblBtnConnect);
			}
		}
	}

	public void resetInterface() {
		btnHeat.setChecked(false);
		btnBed.setChecked(false);

	}

	public boolean onOptionsItemSelected(MenuItem item) {

		// Handle item selection
		switch (item.getItemId()) {
		case R.id.action_loadFile:
			Intent intent = new Intent(this, DrivePicker.class);
			startActivity(intent);
			//openFileDialog();
			return true;
		case R.id.action_settings:

			return true;
		case R.id.action_connect:
			lPrintcore.connect();
			updateMenuTitles();

			return true;
		case R.id.action_reset:
			lPrintcore.reset();

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	/**
	 * Open a FileDialog for choosing the input .gcode file
	 */
	private void openFileDialog() {
		Intent intent = new Intent(getBaseContext(), FileDialog.class);
		intent.putExtra(FileDialog.START_PATH, Environment
				.getExternalStorageDirectory().getPath());
		intent.putExtra(FileDialog.SELECTION_MODE, SelectionMode.MODE_OPEN);

		// can user select directories or not
		intent.putExtra(FileDialog.CAN_SELECT_DIR, false);

		intent.putExtra(FileDialog.FORMAT_FILTER, new String[] { "gcode" });

		startActivityForResult(intent, REQUEST_LOAD);
	}

	public synchronized void onActivityResult(final int requestCode,
			int resultCode, final Intent data) {

		if (resultCode == Activity.RESULT_OK) {

			if (requestCode == REQUEST_SAVE) {
				System.out.println("Saving...");
			} else if (requestCode == REQUEST_LOAD) {
				System.out.println("Loading...");
			}

			String filePath = data.getStringExtra(FileDialog.RESULT_PATH);

			// Start LoadTHread
			new LoadFileFromDisk().execute(filePath);

			Toast toast = Toast.makeText(this, filePath, Toast.LENGTH_LONG);
			toast.show();

		} else if (resultCode == Activity.RESULT_CANCELED) {
			// "file not selected");
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		lPrintcore.pause();
	}

	@Override
	protected void onResume() {
		super.onResume();

		lPrintcore.resume();
		updateMenuTitles();

	}

	void logReceivedData(String aLine) {
		mDumpTextView.append(aLine);
		mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
	}

	void updateTitleView(String aMessage) {
		mTitleTextView.setText(aMessage);
	}

	/**
	 * @return the data
	 */
	public List<String> getData() {
		return data;
	}

	/**
	 * @param data
	 *            the data to set
	 */
	public void setData(List<String> data) {
		this.data = data;
	}

	/**
	 * Showing Dialog
	 * */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case progress_bar_type:
			if (progressOpen) {
				pDialog = new ProgressDialog(this);
				pDialog.setMessage(getString(R.string.loading_file_please_stand_by_)
						+ "\n");
				pDialog.setIndeterminate(false);
				pDialog.setMax(100);

				pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				pDialog.setCancelable(false);
				pDialog.show();
				return pDialog;
			}
			return null;

		default:
			return null;
		}
	}

	/**
	 * Background Async Task to download file
	 * */
	class LoadFileFromDisk extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Bar Dialog
		 * */
		@SuppressWarnings("deprecation")
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressOpen = true;
			showDialog(progress_bar_type);
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@SuppressWarnings("deprecation")
		@Override
		protected void onPostExecute(String file_url) {
			logReceivedData("Load finished. Read "
					+ String.valueOf(getData().size() + 1) + " Lines.");
			progressOpen = false;
			dismissDialog(progress_bar_type);
			// pDialog.dismiss();
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
			pDialog.setProgress(Integer.parseInt(progress[0]));
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			try {
				loadFile(params[0]);

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		public int loadFile(String filePath) throws IOException,
				FileNotFoundException {
			File myFile = new File(filePath);
			FileInputStream fIn = null;
			BufferedReader myReader = null;

			int readLines = -1;
			try {

				fIn = new FileInputStream(myFile);
				myReader = new BufferedReader(new InputStreamReader(fIn));
				String aDataRow = "";

				long fileLength = (int) (myFile.length() / 30); // on average 30
																// bytes per
																// line

				// file is found, we delete the old data
				getData().clear();
				readLines = 0;
				while ((aDataRow = myReader.readLine()) != null) {
					getData().add(aDataRow + "\n");
					readLines++;
					publishProgress(""
							+ (int) (((readLines) * 100) / fileLength));

				}
				readLines = getData().size();

			} finally {
				if (myReader != null)
					myReader.close();

				if (fIn != null) {
					fIn.close();

				}

			}
			return readLines;

		}

	}

	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putBoolean(KEY_progessOpen, progressOpen);
	}

}
